var config = require('../../config');
var request = require('request');
var model = require('../models/MovieSearchModel');
var movieDetailModel = require('../models/MovieDetailModel');
var appUtil = require('../../common/utils/appUtils');
var OAuth = require('wechat-oauth');
// var oauthDao = require('../dao/Oauth2RedisDao');
var oauthDao = require('../dao/OauthDao');
var appUtil = require('../../common/utils/appUtils');

var client = new OAuth(config.app.appid, config.app.appsecret, function (openid, callback) {
    // 传入一个根据openid获取对应的全局token的方法
    // 在getUser时会通过该方法来获取token
    oauthDao.getOauth(openid, function (message, result) {
        console.log('save access token to database success.');
        return callback(null, result);
    });
}, function (openid, token, callback) {
    // 请将token存储到全局，跨进程、跨机器级别的全局，比如写到数据库、redis等
    // 这样才能在cluster模式及多机情况下使用，以下为写入到文件的示例
    // 持久化时请注意，每个openid都对应一个唯一的token!
    oauthDao.setOauth(openid, token, function (message) {
        console.log('save access token to database success.');
        return callback(message);
    });
});

var sign = require('../../common/utils/sign.js');
var jsapiTicketController = require('./JsapiTicketController');
var queryConfig = function (callback, req) {
    var url = req.protocol + '://' + req.host + req.originalUrl; //获取当前url
    var ret = sign(jsapiTicketController.getJsapiTicket(), url);
    console.log(ret);
    callback(ret);
};
/**
 *   影片页控制类   页面显示show开头； 页面  ajax用get开头
 * @type {{}}
 */
module.exports = {
    //页面跳转

    showMovieSearch: function (req, res) {
        var cookie_openid = appUtil.getCookieOpenId(req);
        res.cookie('openid', cookie_openid);
        res.render('filmpage', {
            title: '影片查询',
            layout: false,
            open_id: cookie_openid
        })
    },

    showMovieLibByParams:function (req, res) {
        var pname=req.query.pname;
        pname = appUtil.validParams(pname, '美国');
        var id=req.query.id;
        id = appUtil.validParams(id, 0);

        model.showMovieLibByParams([id,pname],function (result) {

            res.render('moviesearchlib', {
                title: '影吧片库',
                layout: false,
                data:result
            });
        })

    },

    showCinemas: function (req, res) {
        res.render('cinema', {
            layout: false
        })
    },
    /**
     * 显示影片库，
     *
     * @param req
     * index:    1. 最新；2. 最热；3.
     * @param res
     */
    showMovieLib: function (req, res) {
        res.render('moviesearchlib', {
            title: '影吧片库',
            layout: false
        });
        // var index=req.query.index;
        // var page=req.query.page;
        // model.getFilmbyType(null,function (result) {
        //     if (result.isSuccess) {
        //         res.render('moviesearchlib',{
        //             title: '影吧片库',
        //             layout: false,
        //             index:index,
        //             data: result.rows
        //         })
        //     }else {
        //         res.json({
        //             status: 'error',
        //             message: '获取数据失败'
        //         })
        //     }
        // })
    },

    movieSearchlib: function (req, res) {
        var index = req.query.index;
        var page = req.query.page;
        model.getFilmbyType([index, page], function (result) {
            if (result.isSuccess) {
                res.render('moviesearchlib', {
                    title: '影吧片库',
                    layout: false,
                    index: index,
                    data: result.rows
                })
            } else {
                res.json({
                    status: 'error',
                    message: '获取数据失败'
                })
            }
        })
    },
    getMoviesearchlib: model.getMovieSearchlib,
    getMoviesearchLibInfo: function (req, res) {

        var resultData = {};
        var param = {};
        var _param_pageSize = req.body.param_pageSize; //当前页
        if (_param_pageSize === '') {
            _param_pageSize = '0';
        }
        var resultData = {};

        var movieName = '';
        if (!(req.body.movieName == '' || req.body.movieName == undefined)) {
            var _movieName = ' and movie.movie_name like "%' + req.body.movieName + '%" ';
            param.movieName = _movieName;
        } else {
            param.movieName = movieName;
        }
        if (!(req.body.param_pageSize == '' || req.body.param_pageSize == undefined)) {
            param.page = parseInt(req.body.param_pageSize);
        } else {
            param.page = 0;
        }
        // var cinemaCode = '"'+req.body.cinemaCode+'"';
        var sort = ' order by ';                        //排序
        if (req.body.sort == 0) {
            sort += 'movietp.publishdate desc';
            // }else if( req.body.sort == 1 ){
            //     sort += '';
        } else if (req.body.sort == 2) {
            sort += 'movietp.score desc ';
        } else {
            sort += 'movietp.publishdate desc';
        }
        if (!req.body.movieType == '') {
            var movieTypes = eval(req.body.movieType);
        } else {
            var movieTypes = '';
        }
        var category = '';
        var movieType = '';
        if (movieTypes.length == 1 && movieTypes[0] == 0) {
            category = '';
        } else {
            for (var i = 0; i < movieTypes.length; i++) {
                if (i >= 1) {
                    movieType += 'and  movietp.category like "%' + movieTypes[i] + '%" '
                } else {
                    movieType += 'WHERE movietp.category like "%' + movieTypes[i] + '%" ';
                }

            }
            category = movieType;
        }
        var country = req.body.movieCountry;
        var _country = '';
        if (country == '0') {
        } else if (country !== undefined) {
            _country = 'and movie.country like "%' + country + '%" ';
        }

        var publishdate = parseInt(req.body.movieYear);
        var _publishdate = '';
        if (!publishdate == 0) {
            if (publishdate >= 2011) {
                _publishdate = 'and DATE_FORMAT(movie.publishdate,"%Y") = ' + publishdate + ' ';
            }
            if (publishdate < 2011 && publishdate >= 2000) {
                _publishdate = 'and DATE_FORMAT(movie.publishdate,"%Y") BETWEEN 2000 and 2010 ';
            }
            if (publishdate < 2000 && publishdate >= 1990) {
                _publishdate = 'and DATE_FORMAT(movie.publishdate,"%Y") BETWEEN 1990 and 2000 ';
            }
            if (publishdate < 1990 && publishdate >= 1980) {
                _publishdate = 'and DATE_FORMAT(movie.publishdate,"%Y") BETWEEN 1980 and 1990 ';
            }
            if (publishdate < 1980) {
                _publishdate = 'and DATE_FORMAT(movie.publishdate,"%Y") < 1980 ';
            }
        }

        // param.cinemaCode= cinemaCode;
        param.sort = sort;
        param.category = category;
        param.country = _country;
        param.publishdate = _publishdate;
        param.page_size = _param_pageSize;
        //根据_param_pageSize查询影吧
        model.getMovieMultiLib(param, function (result) {
            if (!result.isSuccess) {
                res.json({
                    status: 'error',
                    message: '获取最热电影失败'
                })
            } else {
                res.json({
                    status: 'success',
                    data: result.rows
                })
            }
        })
    },
    // postMoviesearchFilter: function (req, res) {
    //
    // },
    // postMoviesearchLibInfoByParam: function (req, res) {
    // },
    getMovieSearchDetail: function (req, res) {
        var openid = appUtil.getCookieOpenId(req);
        openid = appUtil.validParams(openid, '1234');
        var lat,longt
        if(req.cookies&&req.cookies['geo']){

            var geo=req.cookies['geo'];
            var str = geo.split('-');
             lat=str[0];
             longt=str[1];



        }
        model.getMovieDetailInfoModel(req,[openid,lat,longt], function (data) {
        // var openid = appUtil.getCookieOpenId(req);
        // model.getMovieDetailInfoModel(req,[openid,31,121], function (data) {
            res.render('moviesearchdetail', data)
        });
    },
    getPageHome: function (req, res) {
        var cookie_openid;
        if(req.signedCookies.openid) {
            cookie_openid = req.signedCookies.openid;
            queryConfig(function (ret) {
                res.render('moviehome', {
                    title: '观影频道',
                    layout: false,
                    sign_pkg: ret.jsapi_ticket,
                    appId: config.app.appid,
                    timestamp: ret.timestamp,
                    nonceStr: ret.nonceStr,
                    signature: ret.signature,
                    open_id: cookie_openid,
                    sdkKey:config.amap.sdkKey
                });
            }, req);
        }else{
            client.getAccessToken(req.query.code, function (err, result) {
                if (err) {
                    res.render('error', {
                        title: '服务器出错',
                        message: '获取accesstoken失败',
                        layout: false
                    });
                } else {
                    var openid = result.data.openid;
                        queryConfig(function (ret) {
                        res.cookie('openid', openid, {maxAge:1000*60*60*24,signed:true});
                        res.render('moviehome', {
                            title: '观影频道',
                            layout: false,
                            sign_pkg: ret.jsapi_ticket,
                            appId: config.app.appid,
                            timestamp: ret.timestamp,
                            nonceStr: ret.nonceStr,
                            signature: ret.signature,
                            open_id: openid,
                            sdkKey:config.amap.sdkKey
                        });
                    }, req);
                 }
            });
        }
    },
    getmoviesearch: function (req, res) {
            var open_id = appUtil.getCookieOpenId(req);
            model.getPageData(null, function (result) {
                if (!result.isSuccess) {
                    res.json({
                        status: 'error',
                        message: '获取数据失败'
                    })
                }
                res.render('moviesearch', {
                    title: '影片频道',
                    layout: false,
                    data: result.data,
                    open_id:open_id
                })
            })


    },

    // // ajax部分
    // /**
    //  * 最新电影
    //  * @param req
    //  * @param res
    //  */
    // getNewFilm: function (req, res) {
    //
    //     model.getNewFilm([0, 3], function (reslut) {
    //
    //         if (!reslut && !reslut.isSuccess) {
    //             res.json({
    //                 status: 'error',
    //                 message: '获取最新电影失败'
    //             })
    //         }
    //
    //         res.json({
    //             status: 'success',
    //             data: reslut.rows
    //         })
    //     })
    // },
    // /**
    //  * 最热电影
    //  * @param req
    //  * @param res
    //  */
    // getHotFilm: function (req, res) {
    //     var page = req.query.page;
    //     var begin = pageSize * (page - 1);
    //     model.getHotFilm([begin, pageSize], function (result) {
    //         if (!result.isSuccess) {
    //             res.json({
    //                 status: 'error',
    //                 message: '获取最热电影失败'
    //             })
    //         }
    //         res.json({
    //             status: 'success',
    //             data: reslut.rows
    //         })
    //     })
    // },
    // /**
    //  * 电影评分列表
    //  * @param req
    //  * @param res
    //  */
    // getScoreFilm: function (req, res) {
    //     var page = req.query.page;
    //     var begin = pageSize * (page - 1);
    //     model.getScoreFilm([begin, pageSize], function (result) {
    //         if (!result.isSuccess) {
    //             res.json({
    //                 status: 'error',
    //                 message: '获取评分电影失败'
    //             })
    //         }
    //         res.json({
    //             status: 'success',
    //             data: reslut.rows
    //         })
    //     })
    // },
    /**
     *
     * @param req
     * @param res
     */
    getPageData: function (req, res) {
        var cookie_openid = appUtil.getPostOpenid(req);

        model.getPageData(null, function (result) {
            if (!result.isSuccess) {
                res.json({
                    status: 'error',
                    message: '获取数据失败'
                })
            }
            res.json({
                status: 'success',
                data: result.data,
                open_id: cookie_openid
            })
        })
    }
};
console.log(process.cwd());

